const { addBlogType, getBlogType, deleteBlogTypes, getOneBlogTypes, updateOneBlogTypes } = require("../Dao/blogTypeDao");
const { FormatJson } = require("../utils/tool");
const { DataFaildError } = require("../utils/errors");
const validate = require("validate.js");
const { getAllBlog } = require("../Dao/blogDao");
// 获取文章分类
module.exports.getBlogTypeServices = async function () {
    const data = await getBlogType();
    // 过滤掉deleteAt属性
    for (const items of data) {
        delete items.deletedAt
    }
    // 进行数据排序
    data.sort((a, b) => a.order - b.order)
    return FormatJson(0, "", data)
}

// 添加文章分类
module.exports.addBlogTypeServices = async function (info) {
    // 进行规则判断
    const BlogTypesRule = {
        name: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        order: {
            presence: {
                allowEmpty: false
            },
            numericality: {
                strict: true
            }
        }
    }
    // 通过
    const data = validate.validate(info, BlogTypesRule);
    if (data) {
        throw new DataFaildError(JSON.stringify(data));
    }
    let result = await addBlogType(info);
    result = {
        name: result.name,
        order: result.order
    }
    return FormatJson(0, "", result);
}

// 删除文章分类
module.exports.deleteOneBlogTypeServices = async function (id) {
    const result = await deleteBlogTypes(id);
    const BlogNumbers = await getAllBlog(id);
    return result > 0 ? FormatJson(0, "", BlogNumbers) : FormatJson(0, "", false);
}

// 更新文章分类
/**
 * 
 * @param {*} id 分类id
 * @param {*} info 分类内容的
 */
module.exports.updateOneBlogTypeServices = async function (id, info) {
    await updateOneBlogTypes(id, info);
    const result = await getOneBlogTypes(id);
    delete result.deletedAt;
    return FormatJson(0, "", result)
}

// 一个文章分类
module.exports.getOneBlogTypeServices = async function (id) {
    const result = await getOneBlogTypes(id);
    delete result.deletedAt;
    return FormatJson(0, "", result)
}